import React, { Component } from 'react';
import { Card, Modal, message } from 'antd';
import { connect } from 'dva';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoTable from '@/components/common/PateoTable';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import QueryDetail from './vehicleConfigLogQueryDetail';
import router from 'umi/router';
import moment from 'moment';

interface btnItemType {
  id: number;
  [propName: string]: any;
}
interface iProps {
  dispatch: any;
  dataPermission: dataPermissionType;
  loading: boolean;
  location: any;
}
interface dataPermissionType {
  pageData: pageDataType;
}
interface pageDataType {
  list: Array<dataListType>;
  pageNo: number;
  pageCount: number;
  pageSize: number;
  itemSize: number;
}
interface dataListType {
  id: number;
  vin: string;
  configType: string;
  requestTime: string;
  versionTime: string;
  configTime: string;
  responseTime: string;
  configResult: string;
  serialNum: string;
  pageNo: number;
  pageCount: number;
  pageSize: number;
  itemSize: number;
}
interface iState {
  formValues: formValuesType;
  isModalOpen: boolean;
}
interface formValuesType {
  configType?: string;
}

const mapStateToProps = (state: any) => {
  return {
    // dataPermission: state.http,
    vehicleConfigLogQuery: state.vehicleConfigLogQuery,
    loading: state.loading.effects['vehicleConfigLogQuery/getFetchPage'],
  };
};

class index extends Component<any, any> {
  constructor(props: any) {
    super(props);   
    this.state = {
      extendStatus: false,
      formValues: {
        startTime: moment()
          .add(-1, 'week')
          .valueOf(),
        endTime: moment().valueOf(),
        vin: undefined,
        configType: undefined,
        serialNum: undefined,
      },
      pagination: {
        pageNo: 1,
        // pageCount: 0,
        pageSize: 10,
        // itemSize: 0,
      },
      model: {
        isModalOpen: false,
        id: 0,
      },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { pagination, formValues } = this.state;
    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location
      let values = {
        ...pagination,
      }
      if ( sourcePage === 'vehicleConfigLogQueryDetail' ) {
        const tempValues = sessionStorage.getItem('vehicleConfigLogQuerySearchValues');
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {})
        }
        this.setState({
          extendStatus: true,
        })
      }

      const { pageNo, pageSize, ...rest } = values;
      this.setState({
        formValues: {
          ...formValues,
          ...rest,
        },
        pagination: {
          pageNo,
          pageSize
        }
      }, () => {
        const { formValues, pagination } = this.state;
        this.searchForm.current.setFieldsValue({
          ...formValues,
          startTime: moment(formValues.startTime),
          endTime: moment(formValues.endTime),
        });
        dispatch({
          type: 'vehicleConfigLogQuery/getFetchPage',
          payload: { url: '/connectLog/configLogList', ...pagination, ...formValues },
        });
      })

    })
  }

  componentWillUnmount() {
    if(this.unlisten) {
      this.unlisten();
    }
  }

  handleCancel = () => {
    this.setState({
      model: {
        isModalOpen: false,
        id: 0,
      },
    });
  };

  render() {
    const selectOptions = [
      {
        value: 1,
        label: '蓝牙钥匙',
      },
      {
        value: 2,
        label: '通用配置修改',
      },
      {
        value: 3,
        label: 'CAN网络异常监控参数配置',
      },
      {
        value: 4,
        label: '金融授信参数配置',
      },
    ];

    const { formValues,  model, extendStatus } = this.state;
    const searchItems = [
      {
        type: 'datePicker',
        title: '请求时间起',
        key: 'startTime',
        showTime: { format: 'HH:mm:ss' },
        format: 'YYYY-MM-DD HH:mm:ss',
        rules: [{ required: true, message: '请求开始时间必选!' }],
        initialValue: moment(formValues.startTime),
      },
      {
        type: 'datePicker',
        title: '请求时间止',
        key: 'endTime',
        showTime: { format: 'HH:mm:ss' },
        format: 'YYYY-MM-DD HH:mm:ss',
        rules: [{ required: true, message: '请求结束时间必选!' }],
        initialValue: moment(formValues.endTime),
      },
      {
        type: 'input',
        title: 'VIN码',
        key: 'vin',
        rules: [
          {
            required: false,
            message: '请输入10-17的英文和数字',
            min: 10,
            max: 17,
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
      },
      {
        type: 'select',
        title: '配置类型',
        key: 'configType',
        selectOptions,
      },
      {
        type: 'input',
        title: '唯一流水号',
        key: 'serialNum',
        maxLength: 18,
      },
    ];
    const {
      // dataPermission,
      vehicleConfigLogQuery: {
        pageData: { list, pageCount, pageNo, pageSize, itemSize },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;

    // const { list = [], ...pagination } = dataPermission?.pageData || {};
    const pagination = { 
      current: pageNo, 
      pageSize: pageSize, 
      total: itemSize 
    }

    /* const newPage = {
      ...pageSize,
      ...pagination,
      current: pagination.pageNo || pageSize.pageNo,
      total: pagination.itemSize || pageSize.pageCount,
    }; */

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      // ...newPage,
      ...pagination,
      showTotal: () => <span>共&nbsp;{pagination.total}&nbsp;条</span>,
    };
    const columns = [
      {
        title: 'VIN码',
        dataIndex: 'vin',
      },
      {
        title: '配置类型',
        dataIndex: 'configType',
        render: (text: string) => {
          const item = selectOptions.find(e => e.value === parseInt(text));
          return item?.label;
        },
      },
      {
        title: '下发指令时间',
        dataIndex: 'requestTime',
      },
      {
        title: '回复版本时间',
        dataIndex: 'versionTime',
      },
      {
        title: '下发配置时间',
        dataIndex: 'configTime',
      },
      {
        title: '回复配置结果时间',
        dataIndex: 'responseTime',
      },
      {
        title: '配置结果状态',
        dataIndex: 'configResult',
        render(text: string) {
          return text === '0' ? '成功' : text === '1' ? '失败' : text === '2' ? '参数超限' : '';
        },
      },
      {
        title: '唯一流水号',
        dataIndex: 'serialNum',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 80,
        fixed: 'right',
        render: (text: any, record: btnItemType) => {
          const btns = [
            {
              title: '详情',
              key: 'show',
              auth: 'vehicleConfigLogQuery_show',
              onConfirm: () => {
                // this.setState({
                //   model: {
                //     isModalOpen: true,
                //     id: record.id,
                //   },
                // });
                const { formValues, pagination } = this.state;
                const searchValues = {
                  ...formValues,
                  ...pagination,
                };
                sessionStorage.setItem('vehicleConfigLogQuerySearchValues', JSON.stringify(searchValues));
                router.push(
                  `/connectPlat/vehicleConfigLogQuery/vehicleConfigLogQueryDetail?id=${record.id}`,
                );
              },
            },
          ];

          return <PateoAuthButtons btns={btns} max="1" pathname={pathname} />;
        },
      },
    ];
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onChange: (page: any, filters: any) => {
        const { dispatch } = this.props;
        const { current, pageSize } = page
        const params = {
          ...formValues,
          pageNo: current,
          pageSize: pageSize,
          ...filters,
        };
        this.setState({
          pagination: {
            pageNo: current,
            pageSize: pageSize
          },
        }, () => {
          dispatch({
            type: 'vehicleConfigLogQuery/getFetchPage',
            payload: { url: '/connectLog/configLogList', ...params },
          });
        });
      },
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{ type: 'vehicleConfigLogQuery/getFetchPage', url: '/connectLog/configLogList' }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: {
                  ...formValues,
                  ...val,
                },
              });
            }}
            handleFormReset={() => {
              const startTime = moment()
                .add(-1, 'week')
                .valueOf();
              const endTime = moment().valueOf();
              this.searchForm.current?.resetFields();
              this.searchForm.current.setFieldsValue({
                startTime: moment(startTime),
                endTime: moment(endTime),
              });
              this.setState({
                formValues: { startTime, endTime },
                pagination: {
                  pageNo: 1,
                  pageSize: 10,
                },
              });
            }}
            handleFieldsValue={(val: any) => {
              const { startTime, endTime } = val;
              const { pageNo, pageSize } = this.state.pagination;

              if (!startTime) {
                message.warning('请选择请求开始时间');
                return false;
              }
              if (!endTime) {
                message.warning('请选择结束开始时间');
                return false;
              }
              const { configType, serialNum, vin } = val;
              return {
                ...val,
                pageNo,
                pageSize,
                configType: configType || undefined,
                serialNum: serialNum || undefined,
                vin: vin || undefined,
                startTime: startTime ? startTime.valueOf() : '',
                endTime: endTime ? endTime.valueOf() : '',
              };
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable tableProps={tableProps} formValues={formValues} />
        </Card>
        <Modal
          title="日志详情（CAN网络异常监控配置）"
          visible={model.isModalOpen}
          onCancel={this.handleCancel}
          footer={null}
          width={'80%'}
          style={{ minWidth: '1200px' }}
        >
          <QueryDetail id={model.id} onBack={this.handleCancel}></QueryDetail>
        </Modal>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
